package com.g4m.baselib.fegin;

import com.g4m.baselib.entity.SnsNdkPublic;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * Created on 2020-01-01
 * <p>Copyright 2008-2020 snsndk.com</p>
 */
@Slf4j
public class FeginPublicDataHolder {
    private static final HystrixRequestVariableDefault<HttpServletRequest> HYSTRIX_REQUEST_CONTEXT = new HystrixRequestVariableDefault<>();


    /**
     * 获取请求公共P信息
     *
     * @param httpRequest HttpServletRequest
     * @return SnsNdkPublic
     */
    public static SnsNdkPublic getSnsNdkPublic(HttpServletRequest httpRequest) {
        Object snsNdkPublicObj = httpRequest.getAttribute("snsNdkPublic");
        if (snsNdkPublicObj instanceof SnsNdkPublic) {
            return (SnsNdkPublic) snsNdkPublicObj;
        }
        return null;
    }

    /**
     * 获取请求公共P信息
     *
     * @param httpRequest  HttpServletRequest
     * @param snsNdkPublic SnsNdkPublic
     */
    public static void setSnsNdkPublic(HttpServletRequest httpRequest, SnsNdkPublic snsNdkPublic) {
        httpRequest.setAttribute("snsNdkPublic", snsNdkPublic);
    }

    /**
     * 执行完后清除现场
     *
     * @param httpRequest 请求
     */
    public static void clear(HttpServletRequest httpRequest) {
        if (httpRequest != null) {
            httpRequest.removeAttribute("snsNdkHeader");
            httpRequest.removeAttribute("snsNdkPublic");
        }
        if (HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.getContextForCurrentThread().shutdown();
        }
    }

    /**
     * 获取httpRequest上下文
     *
     * @return 上下文
     */
    public static HttpServletRequest getHttpServletRequest() {
        initHystrixRequestContext();
        return HYSTRIX_REQUEST_CONTEXT.get();
    }

    /**
     * 设置httpRequest上下文
     *
     * @param httpRequest 请求
     */
    public static void setHttpServletRequest(HttpServletRequest httpRequest) {
        initHystrixRequestContext();
        HYSTRIX_REQUEST_CONTEXT.set(httpRequest);
    }

    /**
     * 初始化
     */
    private static void initHystrixRequestContext() {
        if (!HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.initializeContext();
        }
    }
}
